package com.example.handler;


import com.example.common.annotation.MyTransactional;
import com.example.dao.UserMapper;
import com.example.pojo.User;
import com.example.utils.TransactionalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {
    @Autowired
    private TransactionalUtil transactionalUtil;
    public static int i = 1;

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("test")
    public String test() {
        userMapper.selectUserById(1);
        return "";
    }


    @RequestMapping("test2")
    @ResponseBody
    @Transactional
    public String ttt() {
//        DataSourceTransactionManager   手动事物支持 ,开启事物 ,提交 / 回滚操作
        User user = new User();
        try {
            int count1 = userMapper.insert(user);
            int count2 = userMapper.insert(user);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return "11";
    }

    @RequestMapping("test3")
    @ResponseBody
    public String tt3t() {
        User user = new User();
        TransactionStatus begin = null;
        try {
            begin = transactionalUtil.begin();
            int count1 = userMapper.insert(user);
            int count2 = userMapper.insert(user);
            int c = 1 / 0;
            transactionalUtil.submit(begin);
        } catch (Exception e) {
            if (begin != null) {
                transactionalUtil.rollback(begin);
            }
            e.printStackTrace();
        }
        return "11";
    }

    @RequestMapping("test4")
    @ResponseBody
    @MyTransactional
    public String ttt4() {
        try {
            User user = new User();
            int count1 = userMapper.insert(user);
            int count2 = userMapper.insert(user);
            int c = 1 / 0;
            return "";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
